<template>
  <div :class="{ 'sync-stopped-by-system': isSyncStopped }">
    <ResourceTable
      ref="tableRef"
      :resource-name="resourceName"
      :table-id="tableId"
      :action-request-params="actionRequestParams"
      :data-request-query-string="dataRequestQueryString"
    >
      <template #subject="{ row }">
        <div class="inline-flex max-w-[420px] flex-nowrap items-center">
          <div class="block min-w-0 truncate">
            <MessageSubject
              :subject="row.subject"
              :message-id="row.id"
              :account-id="accountId"
            />
          </div>

          <div
            v-if="row.tags"
            class="-mt-1 ml-1 inline-flex shrink-0 space-x-0.5 group-hover/td:hidden"
          >
            <TextBackground
              v-for="tag in row.tags"
              :key="tag.id"
              class="inline-flex items-center rounded-md px-2.5 py-px text-xs/5 font-normal dark:!text-white"
              :text="tag.name"
              :color="tag.swatch_color"
            />
          </div>
        </div>
      </template>

      <template #from="{ row }">
        <MessageRecipient v-if="row.from" :recipient="row.from" />

        <p
          v-else
          v-text="'(' + $t('mailclient::inbox.unknown_address') + ')'"
        />
      </template>

      <template #date="{ row }">
        {{ formatMessageDate(row.date) }}
      </template>
    </ResourceTable>
  </div>
</template>

<script setup>
import { ref } from 'vue'

import { useDates } from '@/Core/composables/useDates'

import MessageRecipient from '../Emails/MessageRecipient.vue'

import MessageSubject from './InboxMessageSubject.vue'

defineProps({
  tableId: { required: true, type: String },
  dataRequestQueryString: { type: Object, required: true },
  actionRequestParams: { type: Object, required: true },
  isSyncStopped: Boolean,
  accountId: { type: Number, required: true },
})

const resourceName = Innoclapps.resourceName('emails')

const { DateTime, localizedDate, localizedTime } = useDates()

const tableRef = ref(null)

function formatMessageDate(date) {
  const dateTimeInstance = DateTime.fromISO(date)

  return dateTimeInstance.hasSame(DateTime.now(), 'day')
    ? localizedTime(dateTimeInstance.toISO())
    : localizedDate(dateTimeInstance.toISO())
}

defineExpose({ tableRef })
</script>

<style>
.read td {
  @apply !font-normal;
}
.unread td {
  @apply !bg-neutral-50/80 !font-semibold dark:!bg-neutral-800;
}
</style>
